import React from 'react';
import { Table, Button, Row, Empty, Spin } from 'antd';
import { router, withRouter } from 'umi';
import moment from 'moment';
import { isArray } from 'lodash';
import { Pagination } from '@/components';
import { useRequest, defaultFormatResult } from '@/hooks';
import { Link } from '../../../components';
import HistoryTotalForm from '../HistoryTotalForm';
import { getChannelRecordCount, getResumeRecordCount, getEmailRecordCount } from '../../service';
import { getChannelListWithoutTalent } from '../../../Setting/service';
import styles from './index.less';

const dateItem = title => ({
    dataIndex: 'operateDate',
    title: (
        <div className={styles.theadWrap}>
            <span className={styles.theadItem} style={{ left: 16, bottom: 6 }}>
                时间
            </span>
            <span className={styles.theadItem} style={{ left: 12, top: 10 }}>
                {title}
            </span>
            <span className={styles.theadItem} style={{ right: 16, top: 12 }}>
                渠道
            </span>
        </div>
    ),
    width: 170,
    fixed: 'left'
});

const TYPE = {
    publish: {
        service: getChannelRecordCount,
        title: '岗位数(个)'
    },
    resume: {
        service: getResumeRecordCount,
        title: '简历数(份)'
    },
    email: {
        service: getEmailRecordCount,
        title: '简历数(份)'
    }
};

const HistoryTotal = ({ location, type = 'publish' }) => {
    const { query = {} } = location;

    const { data: recordData, loading, run: fetchDetail } = useRequest(TYPE[type].service, {
        manual: true,
        ...defaultFormatResult
    });

    const { data: channelList, run: fetchChannelList } = useRequest(
        () => getChannelListWithoutTalent({ channelStatus: 1 }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );

    const sortList = React.useMemo(() => channelList?.map(item => item.channelCode) || [], [channelList]);

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        history.push({ query: { ...query, pageNo: current, pageSize } });
    };

    const getColumns = () => {
        let columns = [];
        const data = recordData?.rows || [];
        if (data && data.length > 0) {
            const keys = Object.keys(data[0]);
            let arr = [];
            if (type === 'email') {
                arr = keys
                    .filter(item => item !== 'operateDate')
                    .map(item => ({
                        dataIndex: item,
                        title: item,
                        render: (text, record) => (
                            <Link
                                to={{
                                    pathname: '/office/personnelManagement/recruitment/email/history/detail',
                                    query: {
                                        fetchMail: item,
                                        operateEndDate:
                                            record.operateDate === '合计'
                                                ? recordData?.rows[0].operateDate
                                                : record.operateDate,
                                        operateStartDate:
                                            record.operateDate === '合计'
                                                ? recordData?.rows[recordData?.rows.length - 1].operateDate
                                                : record.operateDate
                                    }
                                }}
                            >
                                {text}
                            </Link>
                        )
                    }));
            } else {
                arr = sortList
                    .filter(item => keys.includes(item))
                    .map(item => ({
                        dataIndex: item,
                        title: channelList?.find(v => v.channelCode === item)?.channelName,
                        render: (text, record) => {
                            let operateType = null;
                            if (type === 'publish') {
                                if (!query?.operateType) {
                                    operateType = {
                                        operateType: '1'
                                    };
                                }
                                if (query?.operateType && query?.operateType !== '0') {
                                    operateType = {
                                        operateType: query?.operateType
                                    };
                                }
                            }
                            return (
                                <Link
                                    to={{
                                        pathname: '/office/personnelManagement/recruitment/channel/history/list',
                                        query: {
                                            activeKey: type === 'publish' ? '1' : '2',
                                            channelCode: item,
                                            ...operateType,
                                            operateEndDate:
                                                record.operateDate === '合计'
                                                    ? recordData?.rows[0].operateDate
                                                    : record.operateDate,
                                            operateStartDate:
                                                record.operateDate === '合计'
                                                    ? recordData?.rows[recordData?.rows.length - 1].operateDate
                                                    : record.operateDate
                                        }
                                    }}
                                >
                                    {text}
                                </Link>
                            );
                        }
                    }));
            }
            columns = [dateItem(TYPE[type].title)].concat(arr);
        }
        return columns;
    };

    const getFinalData = () => {
        const data = recordData?.rows || [];
        const keys = Object.keys(data[0]);
        const total = {};
        data.forEach(item => {
            keys.forEach(k => {
                if (k === 'date') {
                    return;
                }
                if (total[k]) {
                    total[k] += item[k];
                } else {
                    total[k] = item[k];
                }
            });
        });
        return data.concat([{ ...total, operateDate: '合计' }]);
    };

    React.useEffect(() => {
        const {
            channelType = '',
            operateType = '1',
            operateStartDate,
            operateEndDate,
            dateQuick,
            channelCodes = [],
            activeKey,
            ...rest
        } = query;
        let params = null;
        if (type === 'publish' || type === 'resume') {
            params = {
                channelCodes: isArray(channelCodes) ? channelCodes : [channelCodes],
                channelType: channelType !== '0' && channelType !== '3' ? channelType : '',
                operateType: operateType !== '0' ? operateType : ''
            };
        }
        fetchDetail({
            ...rest,
            ...params,
            operateStartDate:
                operateStartDate ||
                moment()
                    .subtract(6, 'days')
                    .format('YYYY-MM-DD'),
            operateEndDate: operateEndDate || moment().format('YYYY-MM-DD')
        });
    }, [query]);

    React.useEffect(() => {
        if (type === 'publish' || type === 'resume') {
            fetchChannelList(query?.channelCompanyCode ? { channelCompanyCode: query?.channelCompanyCode } : {});
        }
    }, []);

    return (
        <>
            <Row type="flex" justify="space-between" style={{ flexWrap: 'nowrap' }}>
                <HistoryTotalForm type={type} />
                <Button
                    type="primary"
                    style={{ margin: '4px 0' }}
                    onClick={() => {
                        if (type === 'email') {
                            history.push({
                                pathname: '/office/personnelManagement/recruitment/email/history/detail'
                            });
                            return;
                        }
                        history.push({
                            pathname: '/office/personnelManagement/recruitment/channel/history/list',
                            query: {
                                activeKey: type === 'publish' ? '1' : '2'
                            }
                        });
                    }}
                >
                    全部记录
                </Button>
            </Row>
            {recordData?.rows?.length > 0 ? (
                <>
                    <Table
                        rowKey="operateDate"
                        className={styles.centerTable}
                        columns={getColumns()}
                        dataSource={getFinalData()}
                        bordered
                        pagination={false}
                        scroll={{ x: 'max-content' }}
                        style={{ marginTop: 12 }}
                        loading={loading}
                    />
                    <Pagination
                        current={query.pageNo || 1}
                        pageSize={query.pageSize || 10}
                        loading={loading}
                        total={recordData?.total || 0}
                        onChange={handlePaginationChange}
                    />
                </>
            ) : (
                <Spin spinning={loading}>
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ margin: '120px 0' }} />
                </Spin>
            )}
        </>
    );
};

export default withRouter(HistoryTotal);
